package java8.atguigu.teacher.forkjoin;

import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @program lambda
 * @description:
 * @author: zhanglu
 * @create: 2019-05-27 23:15:00
 */
public class TestForkJoin {

    /**
     * ForkJoin 框架
     */
    @Test
    public void test01(){
        Instant start = Instant.now();

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new Calculate(0, 100000000l);
        long sum = pool.invoke(task);
        System.out.println(sum);

        Instant end = Instant.now();

        System.out.println(Duration.between(start, end).toMillis());
    }

    /**
     * 普通for循环
     */
    @Test
    public void test02(){
        Instant start = Instant.now();

        long sum = 0l;
        for(int i=0;i<100000000l; i++){
            sum += i;
        }
        System.out.println(sum);

        Instant end = Instant.now();

        System.out.println(Duration.between(start, end).toMillis());
    }

    /**
     * java8 并行流
     */
    @Test
    public void test03() throws UnsupportedEncodingException {
        Instant start = Instant.now();
        long sum = LongStream.rangeClosed(0, 100000000l)   //串行流
                .reduce(0, Long::sum);
        System.out.println(sum);
        Instant end = Instant.now();

        System.out.println(Duration.between(start, end).toMillis());

        start = Instant.now();
        LongStream.rangeClosed(0, 100000000l)   //并行流
                .parallel()
                .reduce(0, Long::sum);
        System.out.println(sum);
        end = Instant.now();

        System.out.println(Duration.between(start, end).toMillis());
    }

}
